//
//  ExpenseListDetailsTableViewController.swift
//  NewCard
//
//  Created by yihui on 2017/11/21.
//  Copyright © 2017年 yihui. All rights reserved.
//

import UIKit

let expenseList = "expenseList"

class ExpenseListDetailsTableViewController: UITableViewController {

    // 属性
    
    // 银行名称
    @IBOutlet weak var bankNameLabel: UILabel!
    // 银行卡号
    @IBOutlet weak var bankCardLabel: UILabel!
    // 固定额度
    @IBOutlet weak var totalLabel: UILabel!
    // 临时额度
    @IBOutlet weak var temporaryAmountLabel: UILabel!
    // 可用额度
    @IBOutlet weak var usableAmountLabel: UILabel!
    // 欠款金额
    @IBOutlet weak var oweLabel: UILabel!
    // 总消费
    @IBOutlet weak var adjShoppingLabel: UILabel!
    // 总还款
    @IBOutlet weak var adjRepayLabel: UILabel!

    @IBOutlet weak var topBar: UIView!
    
    @IBOutlet weak var tabBar: UIView!
    
    // 接收数据
    var cardModel : CardModel!
    
    fileprivate var models : [ExpenseModel]?
    
    var presentFrame = CGRect.zero
    
    // MARK: - 懒加载
    fileprivate lazy var animatorManager = { () -> PopoverManager in
        let manager = PopoverManager()
        let w: CGFloat = 300
        let h: CGFloat = 300
        let x: CGFloat = (self.view.width - w) * 0.5
        let y: CGFloat = (self.view.height - h) * 0.5
        manager.presentFrame = CGRect(x: x, y: y ,width: w, height: h)
        return manager
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        setupUI()
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
 

}

// MARK: -  ui
extension ExpenseListDetailsTableViewController {
    
    fileprivate func setupUI() {
        
        // 不显示cell分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        
        bankNameLabel.text = cardModel.bankName
        bankCardLabel.text = String(cardModel.bankCard)
        totalLabel.text = "总:\(Tools.calculation(cardModel.total))"
        temporaryAmountLabel.text = "临:\(Tools.calculation(cardModel.temporaryAmount))"
        usableAmountLabel.text = "可:\(Tools.calculation(cardModel.usableAmount))"
        oweLabel.text = "欠:\(Tools.calculation(cardModel.total - cardModel.usableAmount))"
        
        topBar.layer.cornerRadius = 10
        tabBar.layer.cornerRadius = 10
        loadData()
       
    }
}

// MARK: - 生命周期
extension ExpenseListDetailsTableViewController {
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        animateTable()
    }
}

// MARK: - Table view data source
extension ExpenseListDetailsTableViewController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return models?.count ?? 0
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = models?[indexPath.row]
        
        let cell = tableView.dequeueReusableCell(withIdentifier: expenseList, for: indexPath) as! ExpenseListCell
        
        cell.layer.cornerRadius = 10
        cell.expensModel = model
        
        return cell
    }
}


// MARK: - Table view delegate
extension ExpenseListDetailsTableViewController {
    // MARK: -- tableView 侧滑按钮
    override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        
        let model = self.models?[indexPath.item]
        
        //右侧第一个按钮
        let actionOne = UITableViewRowAction(style: .normal, title: "删除") {_,_ in
            self.models!.remove(at: indexPath.item)
            // 删除数据
            if !OpenData.deleteData(data: model!) {
                //HHLog("删除失败!")
            }
            // 刷新数据
            self.loadData()
        }
        //背景颜色
        actionOne.backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
        
        return [actionOne]
    }
    
    // MARK: -- tableView 背景颜色设置
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.backgroundColor =  colorforIndex(indexPath.row)
    }
    
    // MARK: -- tableView 背景颜色
    private func colorforIndex(_ index: Int) -> UIColor {
        
        let rowCount = models!.count <= 1 ? 1 : models!.count - 1
        let color = (CGFloat(index) / CGFloat(rowCount)) * 0.6
        return UIColor(red: 1.0, green: color, blue: 0.3, alpha: 0.8)
    }
    
    // MARK: -- tableview cell 动画
    fileprivate func animateTable() {
        let cells = tableView.visibleCells
        let tableHeight: CGFloat = tableView.bounds.size.height
        
        
        for (index, cell) in cells.enumerated() {
            tabBar.alpha = 0.0
            cell.transform = CGAffineTransform(translationX: 0, y: tableHeight)
            UIView.animate(withDuration: 1.0, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
                self.tableView.alpha = 1.0
                cell.transform = CGAffineTransform(translationX: 0, y: 0);
                self.view.layoutIfNeeded()
            }, completion: { (_) in
                
                UIView.animate(withDuration: 0.5, animations: {
                    self.tabBar.alpha = 1.0
                })
            })
            
        }
    }
}

// MARK: -  获取数据
extension ExpenseListDetailsTableViewController {
    
    fileprivate func loadData() {
        
        let array = OpenData.loadData(ExpenseListSelectData: cardModel)
        var tempArr = [ExpenseModel]()
        
        for arr in array! {
            
            tempArr.append(ExpenseModel(dict:arr))
        }
        models = tempArr

        statisticsMoney()

        tableView.reloadData()
    }

    
    private func statisticsMoney() {
        
        var tempAdjShopping : Double = 0
        var tempAdjRepay : Double = 0
        
        for model in models! {
            if model.useType == "消费" {
                tempAdjShopping += model.money
            } else if model.useType == "还款" {
                tempAdjRepay += model.money
            }
        }
        
        adjShoppingLabel.text = "总消:\(Tools.calculation(tempAdjShopping))"
        adjRepayLabel.text = "总还:\(Tools.calculation(tempAdjRepay))"
    }
    

    
}

// MARK: - 点击事件
extension ExpenseListDetailsTableViewController {
    
    @IBAction func popoViewButtonClick(_ sender: Any) {
        
        let sb = UIStoryboard(name: "ExpensePopoverViewController", bundle: nil)
        guard let menuView = sb.instantiateInitialViewController() else {
            return
        }
        let vc = menuView as! ExpensePopoverViewController
        
        vc.models = [cardModel!]
        
        menuView.transitioningDelegate = animatorManager
        menuView.modalPresentationStyle = .custom

        present(menuView, animated: true, completion: nil)

    }
    
    
    
}
